package me.flyray.admin.biz;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.flyray.admin.entity.User;
import me.flyray.admin.entity.UserRole;
import me.flyray.admin.mapper.MenuMapper;
import me.flyray.admin.mapper.UserMapper;
import me.flyray.admin.mapper.UserRoleMapper;
import me.flyray.admin.vo.UserPassword;
import me.flyray.admin.vo.UserPhone;
import me.flyray.common.msg.BaseApiResponse;
import me.flyray.common.vo.admin.AdminUserRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import me.flyray.auth.client.jwt.UserAuthUtil;
import me.flyray.common.biz.BaseBiz;
import me.flyray.common.constant.UserConstant;
import me.flyray.common.msg.ResponseCode;
import me.flyray.common.msg.TableResultResponse;
import me.flyray.common.util.EntityUtils;
import me.flyray.common.util.MD5;
import me.flyray.common.vo.QueryPersonalBaseListRequest;

import lombok.extern.slf4j.Slf4j;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * ${DESCRIPTION}
 *
 * @author wanghaobin
 * @create 2017-06-08 16:23
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class UserBiz extends BaseBiz<UserMapper, User> {

    @Autowired
    private MenuMapper menuMapper;
	@Autowired
	private UserRoleMapper userRoleMapper;
    @Autowired
    private UserAuthUtil userAuthUtil;
    @Autowired
	private BaseUserSkinStyleBiz baseUserSkinStyleBiz;
    
    @Override
    public int insertSelective(User entity) {
        String md5Password = DigestUtils.md5DigestAsHex((DigestUtils.md5DigestAsHex(entity.getPassword().getBytes())+UserConstant.PW_MD5_SALT).getBytes());
        String password = new BCryptPasswordEncoder(UserConstant.PW_ENCORDER_SALT).encode(md5Password);
        entity.setPassword(password);
        return super.insertSelective(entity);
    }
    public User add(Map<String, Object> param) throws Exception {
    	String crtUser = (String) param.get("crtUser");
    	String crtName = (String) param.get("crtName");
    	User entity = EntityUtils.map2Bean(param, User.class);
        String md5Password = DigestUtils.md5DigestAsHex((DigestUtils.md5DigestAsHex(entity.getPassword().getBytes())+UserConstant.PW_MD5_SALT).getBytes());
        String password = new BCryptPasswordEncoder(UserConstant.PW_ENCORDER_SALT).encode(md5Password);
        entity.setPassword(password);
        entity.setCrtTime(new Date());
        entity.setUpdTime(new Date());
        entity.setCrtName(crtName);
        entity.setCrtUser(crtUser);
        entity.setUpdName(crtName);
        entity.setUpdUser(crtUser);
        mapper.addUser(entity);
		UserRole userRole = new UserRole();
		userRole.setUserId(entity.getUserId());
		userRole.setRoleId((String) param.get("roleId"));
		userRoleMapper.insert(userRole);
        return entity;
    }

    @Override
    public void updateSelectiveById(User entity) {
        super.updateSelectiveById(entity);
    }

    /**
     * 根据用户名获取用户信息
     * @param username
     * @return
     */
    public User getUserByUsername(String username){
        User user = new User();
        user.setUsername(username);
        return mapper.selectOne(user);
    }
    
    /**
     * 根据手机号获取用户信息
     * @param mobilePhone
     * @return
     */
    public User getUserByMobilePhone(String mobilePhone){
        User user = new User();
        user.setMobilePhone(mobilePhone);;
        return mapper.selectOne(user);
    }

	public int addUser(User entity) {
		return mapper.addUser(entity);
	}

	public TableResultResponse<User> pageList(@RequestBody AdminUserRequest bean){
		Example example = new Example(User.class);
		Criteria criteria = null;
		if(!"".equals(bean.getPlatformId()) && null != bean.getPlatformId()){
			if(criteria == null){
				criteria = example.createCriteria();
			}
			//是平台管理员
			criteria.andEqualTo("platformId", bean.getPlatformId());
		}else {
			//系统管理员
		}
		if(!"".equals(bean.getUsername()) && null != bean.getUsername()){
			if(criteria == null){
				criteria = example.createCriteria();
			}
			criteria.andLike("username", "%" + bean.getUsername() + "%");
		}
		if(!StringUtils.isEmpty(bean.getMobilePhone())){
			if(criteria == null){
				criteria = example.createCriteria();
			}
			criteria.andEqualTo("mobilePhone",  bean.getMobilePhone() );
		}
		if(!StringUtils.isEmpty(bean.getParentName())){
			if(criteria == null){
				criteria = example.createCriteria();
			}
			criteria.andLike("parentName",  "%" + bean.getParentName() + "%");
		}
		if(!StringUtils.isEmpty(bean.getUserType()) && bean.getUserType() != 1){
			if(criteria == null){
				criteria = example.createCriteria();
			}
			criteria.andEqualTo("userType",  bean.getUserType() );
		}
		if(!StringUtils.isEmpty(bean.getUserId())){
			if(criteria == null){
				criteria = example.createCriteria();
			}
			criteria.andEqualTo("userId",  bean.getUserId() );
		}
        if(!StringUtils.isEmpty(bean.getDeptId())){
            if(criteria == null){
                criteria = example.createCriteria();
            }
            criteria.andEqualTo("deptId",  bean.getDeptId() );
        }
		example.setOrderByClause("crt_time desc");
		Page<User> result = PageHelper.startPage(bean.getPage(), bean.getLimit());
		List<User> list = mapper.selectByExample(example);
		return new TableResultResponse<User>(result.getTotal(), list);
	}
	
	public static void main(String[] args){
		String md5Password = DigestUtils.md5DigestAsHex((DigestUtils.md5DigestAsHex("c2b1362e33d510904a738cf4ae16ae02".getBytes())+UserConstant.PW_MD5_SALT).getBytes());
		log.info("加密md5Password的密码:" + md5Password);
		String passwordEncoder = new BCryptPasswordEncoder(UserConstant.PW_ENCORDER_SALT).encode(md5Password);
		log.info("bcrypt密码:" + passwordEncoder);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(UserConstant.PW_ENCORDER_SALT);
        log.info("bcrypt密码对比:" + encoder.matches(md5Password, passwordEncoder));

    }
	
	/**
	 * 修改用户密码
	 * @author centerroot
	 * @time 创建时间:2018年8月27日下午3:03:22
	 * @param req
	 * @return
	 */
    public Map<String, Object> updateUserPwd(UserPassword req) {
    	log.info("修改用户密码请求参数:{}",EntityUtils.beanToMap(req));
    	Map<String, Object> respMap = new HashMap<String, Object>();
    	User queryUser=new User();
    	queryUser.setUserId(req.getUserId());
    	User user = mapper.selectOne(queryUser);
    	if (user == null) {
    		respMap.put("code", ResponseCode.USERINFO_NOTEXIST.getCode());
            respMap.put("message", ResponseCode.USERINFO_NOTEXIST.getMessage());
            log.info("修改用户密码响应参数:{}",respMap);
    		return respMap;
		}
    	String md5OldPassword = DigestUtils.md5DigestAsHex((DigestUtils.md5DigestAsHex(req.getPassword().getBytes())+UserConstant.PW_MD5_SALT).getBytes());
    	
		String md5NewPassword = DigestUtils.md5DigestAsHex((DigestUtils.md5DigestAsHex(req.getNewPassword().getBytes())+UserConstant.PW_MD5_SALT).getBytes());
		String NewPassword = new BCryptPasswordEncoder(UserConstant.PW_ENCORDER_SALT).encode(md5NewPassword);
		user.setPassword(NewPassword);
		mapper.updateByPrimaryKeySelective(user);
		respMap.put("code", ResponseCode.OK.getCode());
		respMap.put("message", ResponseCode.OK.getMessage());
    	log.info("修改用户密码响应参数:{}",respMap);
		return respMap;
    }
    
    /**
     * 重置用户密码
     * @author centerroot
     * @time 创建时间:2018年8月27日下午3:31:55
     * @param req
     * @return
     */
    public Map<String, Object> resetUserPwd(UserPassword req) {
    	log.info("重置用户密码请求参数:{}",EntityUtils.beanToMap(req));
    	Map<String, Object> respMap = new HashMap<String, Object>();
    	//User user = mapper.selectByPrimaryKey(req.getId());
    	User queryUser=new User();
    	queryUser.setUserId(req.getUserId());
    	User user = mapper.selectOne(queryUser);
    	if (user == null) {
    		respMap.put("code", ResponseCode.USERINFO_NOTEXIST.getCode());
            respMap.put("message", ResponseCode.USERINFO_NOTEXIST.getMessage());
            log.info("修改用户密码响应参数:{}",respMap);
    		return respMap;
		}
    	
    	String md5pwd = MD5.md5(MD5.md5("123456") + UserConstant.PW_MD5_SALT);
    	
    	String md5NewPassword = DigestUtils.md5DigestAsHex((DigestUtils.md5DigestAsHex(md5pwd.getBytes())+UserConstant.PW_MD5_SALT).getBytes());
        String NewPassword = new BCryptPasswordEncoder(UserConstant.PW_ENCORDER_SALT).encode(md5NewPassword);
        user.setPassword(NewPassword);
        mapper.updateByPrimaryKeySelective(user);
        respMap.put("code", ResponseCode.OK.getCode());
        respMap.put("message", ResponseCode.OK.getMessage());
        
    	log.info("重置用户密码响应参数:{}",respMap);
		return respMap;
    }
    

    /**
     * 用户添加手机号
     * @author centerroot
     * @time 创建时间:2018年11月21日上午11:41:57
     * @param req
     * @return
     */
    public Map<String, Object> addUserPhone(UserPhone req) {
		log.info("用户添加手机号请求参数:{}", EntityUtils.beanToMap(req));
		Map<String, Object> respMap = new HashMap<String, Object>();
		User queryUserByPhone = new User();
		queryUserByPhone.setMobilePhone(req.getNewPhone());
		List<User> userPhones = mapper.select(queryUserByPhone);
		if (null != userPhones && userPhones.size() > 0) {
			respMap.put("code", ResponseCode.MOBILE_REPEAT.getCode());
			respMap.put("message", ResponseCode.MOBILE_REPEAT.getMessage());
			log.info("用户添加手机号响应参数:{}", respMap);
			return respMap;
		}
		User queryUser=new User();
    	queryUser.setUserId(req.getUserId());
    	User user = mapper.selectOne(queryUser);
		//判断原手机号   校验验证码  修改手机号
    	if (!StringUtils.isEmpty(user.getMobilePhone())) {
    		// 存在原手机号，只允许修改不允许添加
    		respMap.put("code", ResponseCode.USERPHONE_ISEXIST.getCode());
			respMap.put("message", ResponseCode.USERPHONE_ISEXIST.getMessage());
			log.info("用户添加手机号响应参数:{}", respMap);
			return respMap;
		}
    	
    	Map<String, Object> validateSmsCodeMap = new HashMap<String, Object>();
		validateSmsCodeMap.put("phone", req.getNewPhone());
		validateSmsCodeMap.put("code", req.getCode());
		//respMap = crmCoreFeign.validateSmsCode(validateSmsCodeMap);
		if (ResponseCode.OK.getCode().equals(respMap.get("code"))) {
			user.setMobilePhone(req.getNewPhone());
			mapper.updateByPrimaryKeySelective(user);
		}
    
		log.info("用户添加手机号响应参数:{}", respMap);
		return respMap;
	}
    
    /**
     * 用户修改手机号
     * @author centerroot
     * @time 创建时间:2018年11月21日上午11:41:57
     * @param req
     * @return
     */
    public Map<String, Object> resetUserPhone(UserPhone req) {
		log.info("用户修改手机号请求参数:{}", EntityUtils.beanToMap(req));
		Map<String, Object> respMap = new HashMap<String, Object>();
		User queryUserByPhone = new User();
		queryUserByPhone.setMobilePhone(req.getNewPhone());
		List<User> userPhones = mapper.select(queryUserByPhone);
		if (null != userPhones && userPhones.size() > 0) {
			respMap.put("code", ResponseCode.MOBILE_REPEAT.getCode());
			respMap.put("message", ResponseCode.MOBILE_REPEAT.getMessage());
			log.info("用户修改手机号响应参数:{}", respMap);
			return respMap;
		}
		User queryUser=new User();
    	queryUser.setUserId(req.getUserId());
    	User user = mapper.selectOne(queryUser);
    	if (!req.getPhone().equals(user.getMobilePhone())) {
    		respMap.put("code", ResponseCode.MOBILE_MATCH_FAIL.getCode());
			respMap.put("message", ResponseCode.MOBILE_MATCH_FAIL.getMessage());
			log.info("用户修改手机号响应参数:{}", respMap);
			return respMap;
		}
    	
    	Map<String, Object> validateSmsCodeMap = new HashMap<String, Object>();
		validateSmsCodeMap.put("phone", req.getNewPhone());
		validateSmsCodeMap.put("code", req.getCode());
		//respMap = crmCoreFeign.validateSmsCode(validateSmsCodeMap);
		if (ResponseCode.OK.getCode().equals(respMap.get("code"))) {
			user.setMobilePhone(req.getNewPhone());
			mapper.updateByPrimaryKeySelective(user);
		}
    
		log.info("用户修改手机号响应参数:{}", respMap);
		return respMap;
	}
    
}
